package client;


import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.Scanner;

public class NettyClient {

    public static void main(String[] args) {
        start();
    }

    public static void start() {

        // 创建EventLoopGroup，用于处理客户端的I/O操作
        EventLoopGroup groupThread = new NioEventLoopGroup();

        try {
            // 创建Bootstrap实例，客户端启动对象
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(groupThread);
            // 设置服务端Channel类型为NioSocketChannel作为通道实现
            bootstrap.channel(NioSocketChannel.class);
            // 设置客户端处理
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    socketChannel.pipeline()

                     .addLast("decoder", new ClientDecoder())
                     .addLast("encoder", new ClientEncoder())
                            .addLast(new ClientHandler());
                }
            });

            // 绑定端口
            ChannelFuture channelFuture = bootstrap.connect("localhost", 9999).sync();
//            channelFuture.channel().closeFuture().sync();
            channelFuture.sync();

            boolean exitFlag = false;
            System.out.print(":> ");
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()) {
                //
                String statStr = scanner.nextLine();
                if ("exit".equals(statStr) || "quit".equals(statStr)) {
                    // 关闭当前
                    exitFlag = true;
                    break;
                }

//                String s1 = PackageUtil.genPkgRaw(statStr);
//                System.out.println("s1 = " + s1);
//                channelFuture.channel().writeAndFlush(Unpooled.copiedBuffer(s1.getBytes()));

                channelFuture.channel().writeAndFlush(statStr);
            }

            if (exitFlag) {
                channelFuture.channel().close();
            }

        } catch (InterruptedException e) {
            System.out.println("xxxxxxxxxxxxxx 被迫终端");
            throw new RuntimeException(e);
        } finally {
            // 优雅地关闭线程
            groupThread.shutdownGracefully();
        }
    }
}